﻿var sid = null;

var upPoints = [];
var downPoints = [];
var pointsMax = 30;

var username;
var password;
var url;
var refresh;

jQuery.support.cors = true;

var rege = new RegExp("<code>X-Transmission-Session-Id: (.*)</code>", "g");

function setSid(xhr, callback)
{
	sid = (rege.exec(xhr.responseText))[1];

	if(callback !=null)
	{
		callback();
	}
}

function Auth(callback) {
	$.ajax({
		type: "POST",
		url: "http://"+url+"/transmission/rpc",
		username: username,
		password: password,
		success: function (response, status, xhr) 
			{
				setSid(xhr, callback);
			},
		error: function (xhr, status, error) 
			{
				if(xhr.status == 409)
				{
					setSid(xhr, callback);
				} 
				else
				{
					$("#error").html = "status: " + xhr.status + "<br/>" + "error: "+error;
				}
				//alert("status: " + xhr.status + "<br/>" + "error: "+error);
			}
			
	});
}

function SessionStats() {

	$("#loading").show();
	
    if (sid == null) 
	{
        Auth(SessionStats);
        return;
    }
	
	$.ajax({
		type: "POST",
		url: "http://"+url+"/transmission/rpc",
		username: username,
		password: password,
		data: '{ "method" : "session-stats"}',
		dataType: "json",
		contentType: "application/json; charset=utf-8",
		beforeSend : function(xhr) 
			{
				xhr.setRequestHeader("X-Transmission-Session-Id", sid);
			},
		success: function (response, status, xhr) 
			{
				if (status == "success") 
				{
					var data = response.arguments;
					$("#downloadSpeed").html(bytesToSpeed(data.downloadSpeed));
					$("#uploadSpeed").html(bytesToSpeed(data.uploadSpeed));
					
					upPoints.push(data.uploadSpeed);
					if (upPoints.length > pointsMax)
					{
						upPoints.splice(0,1);
					}
					$('#uploadSpeedGraph').sparkline(upPoints);
					
					downPoints.push(data.downloadSpeed);
					if (downPoints.length > pointsMax)
					{
						downPoints.splice(0,1);
					}
					$('#downloadSpeedGraph').sparkline(downPoints);
					
					$("#loading").hide();
				}
			},
		error: function (xhr, status, error) 
			{
				$("#error").html = "status: " + xhr.status + "<br/>" + "error: "+error;
			}
	});

}

function loop()
{
	SessionStats();
    setTimeout("loop()", refresh);
}

function onPageLoad() {
	System.Gadget.background = 'images/background_01.png';
	
	System.Gadget.settingsUI = "settings.htm";
	System.Gadget.onSettingsClosed = readSettings;
	
	readSettings();
	loop();
}